import { getUserInfo } from '@/api/login'
import { verifyIsLogin } from '@/api/my'
import storage from '@/utils/storage'
import { defineStore } from 'pinia'
import { ref } from 'vue'

const useStore = defineStore('store', () => {
  const store = ref() // 店铺信息
  const access = ref({
    verificationKey: ''
  }) // 店铺权限信息

  /**
   * 获取用户信息
   * 设计这里的时候有两个想法如下
   * 1.直接更新当前的用户信息，并返回当前的用户信息
   * 2.直接获取当前用户信息
   */
  const fetchUserInfo = async (type = 'refetch') => {
    if (type === 'refetch') {
      return new Promise<any>((resolve, reject) => {
        getUserInfo()
          .then((res) => {
            console.log('用户信息接口返回', res)
            if (res.data.success) {
              storage.setUserInfo(res.data.result)
              store.value = res.data.result
              resolve(res)
            }
          })
          .catch((err) => {
            console.log('baocuole')
            reject(err)
          })
      })
    } else {
      return storage.getUserInfo() || store.value
    }
  }
  // 退出登录
  const signOut = () => {
    storage.setAccessToken('')
    storage.setUserInfo({})
    uni.navigateTo({
      url: '/pages/passport/wechatMPLogin'
    })
  }

  // 验证是否登录
  const verifyLogin = async () => {
    return new Promise<any>((resolve, reject) => {
      verifyIsLogin()
        .then((res) => {
          if (!res.data.result) {
            storage.setAccessToken('')
            storage.setUuid('')
            storage.setUserInfo({})

            // uni.navigateTo({
            //   url: '/pages/passport/wechatMPLogin'
            // })
          }
        })
        .catch((err) => {
          console.log('baocuole')
          reject(err)
        })
    })
  }

  return { store, access, fetchUserInfo, signOut, verifyLogin }
})

export default useStore
